package business

import (
	"errors"
	"vueBasic/app/admin/filter"
	"vueBasic/app/common/model"
	"vueBasic/extend/conv"
	"vueBasic/extend/utils"
)

var AccessB = new(accessBusiness)

type accessBusiness struct {
}

func (*accessBusiness) GetPageList(req *filter.AdminAccessPageReq) ([]*filter.AccessNode, int64, error) {
	AccessList, cnt, err := model.AccessM.GetPageList(req)
	List := make([]*filter.AccessNode, 0)
	for _, v := range AccessList {
		List = append(List, &filter.AccessNode{
			Id:         v.Id,
			ModuleId:   v.ModuleId,
			Type:       v.Type,
			Url:        v.Url,
			Icon:       v.Icon,
			ModuleName: v.ModuleName,
			Sort:       v.Sort,
			Status:     v.Status,
			Children:   nil,
		})
	}
	res := utils.GetTreeRecursive(List, 0, 1)
	return res, cnt, err
}

func (*accessBusiness) GetFieldList() (map[string]interface{}, error) {
	field := "id,module_id,module_name"
	AccessList, err := model.AccessM.GetFieldList(field)
	if err != nil {
		return nil, err
	}
	List := make([]*filter.AdminAccessPid, 0)
	for _, v := range AccessList {
		List = append(List, &filter.AdminAccessPid{
			Id:       conv.Int(v.Id),
			Name:     v.ModuleName,
			Pid:      v.ModuleId,
			Children: nil,
		})
	}
	data := make(map[string]interface{})
	data["pids"] = AccessB.getTreePid(List, 0)
	return data, nil
}

/**
 * @description(格式所属父类树形结构)
 * @buildcode(true)
 */
func (*accessBusiness) getTreePid(list []*filter.AdminAccessPid, pid int) []*filter.AdminAccessPid {
	res := make([]*filter.AdminAccessPid, 0)
	for _, v := range list {
		if v.Pid == pid {
			v.Children = AccessB.getTreePid(list, v.Id)
			res = append(res, v)
		}
	}
	return res
}

func (*accessBusiness) Add(req *filter.AdminAccessAddReq) (uint, error) {
	res, err := model.AccessM.Add(req)
	if err != nil {
		return 0, err
	}
	return res, nil
}

func (*accessBusiness) GetUpdateInfo(req *filter.AdminAccessGetUpdateInfoReq) (any, error) {
	info, err := model.AccessM.GetAccessById(req)
	if err != nil {
		return nil, errors.New("数据不存在")
	}
	return info, nil
}

func (*accessBusiness) Update(req *filter.AdminAccessUpdateReq) (uint, error) {
	res, err := model.AccessM.Update(req)
	if err != nil {
		return 0, errors.New("更新失败")
	}
	return res, nil
}

func (*accessBusiness) UpdateExt(req map[string]interface{}) error {
	err := model.AccessM.UpdateExt(req)
	if err != nil {
		return errors.New("更新失败")
	}
	return nil
}

func (*accessBusiness) Delete(req *filter.AdminAccessDeleteReq) (uint, error) {
	ids := conv.Slice(req.Id)
	if len(ids) > 1 {
		return 0, errors.New("禁止批量删除")
	}
	res, err := model.AccessM.Delete(ids)
	if err != nil {
		return 0, errors.New("删除失败")
	}
	return res, nil
}

func (*accessBusiness) GetRoleUrl(role_id int) []string {
	access := model.RoleAccessM.GetValueByRoleId(role_id, 0)
	urlList := model.AccessM.GetColumnByIds(access, "url")
	return urlList
}
